package com.shopping.service.impl;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.shopping.bean.*;
import com.shopping.dao.OrderDao;
import com.shopping.service.IOrderService;
import com.shopping.util.Page;
import com.shopping.util.PaymentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.math.BigDecimal;
import java.util.*;

@Service
public class OrderService implements IOrderService {
    @Autowired
    private OrderDao orderDao;


    // 生成字母与数字混合的订单号的方法
    private String generateOrderCode() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sdf.format(new Date());
        Random random = new Random();
        StringBuilder randomPart = new StringBuilder();
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(characters.length());
            randomPart.append(characters.charAt(index));
        }
        return timestamp + randomPart.toString();
    }
    @Override
    public void submitOrder(Map<String, Object> orderData) {
        Order order = new Order();
        try {
            int userId = Integer.parseInt(orderData.get("userId").toString());
            order.setUserid(userId);
            order.setOrdertime(new Date());
            BigDecimal totalPayableAmount = new BigDecimal(orderData.get("totalPayableAmount").toString());
            order.setMoney(totalPayableAmount);
            order.setStatus("待付款");
            int addressId = Integer.parseInt(orderData.get("addressId").toString());
            order.setAddressid(addressId);
            int isUpset = Integer.parseInt(orderData.get("isupset").toString());
            order.setIsupset(isUpset);
            // 生成订单号并设置到订单对象中
            String orderCode = generateOrderCode();
            order.setCode(orderCode);
        } catch (NumberFormatException | NullPointerException e) {
            System.err.println("订单数据解析异常: " + e.getMessage());
            throw new RuntimeException("订单数据格式错误", e);
        }

        orderDao.saveOrder(order);
        int orderId = order.getOrderid();

        // 获取地址信息
        String address = orderData.get("address").toString();
        String name = orderData.get("name").toString();
        String tel = orderData.get("tel").toString();

        // 创建 OrderAddress 对象
        OrderAddress orderAddress = new OrderAddress();
        orderAddress.setOrderid(orderId);
        orderAddress.setAddress(address);
        orderAddress.setName(name);
        orderAddress.setTel(tel);

        // 插入地址信息
        addOrderAddress(orderAddress);




        String[] productIds = orderData.get("productIds").toString().split(",");
        String[] productCounts = orderData.get("productCounts").toString().split(",");
        String[] productPrices = orderData.get("productPrices").toString().split(",");

        for (int i = 0; i < productIds.length; i++) {
            Orderinfo orderInfo = new Orderinfo();
            orderInfo.setOrderid(orderId);
            try {
                int productId = Integer.parseInt(productIds[i]);
                orderInfo.setProductid(productId);
                int quantity = Integer.parseInt(productCounts[i]);
                orderInfo.setQuantity(quantity);
                BigDecimal price = new BigDecimal(productPrices[i]);
                orderInfo.setPrice(price);
            } catch (NumberFormatException e) {
                System.err.println("订单详细信息数据解析异常: " + e.getMessage());
                throw new RuntimeException("订单详细信息数据格式错误", e);
            }
            orderDao.saveOrderInfo(orderInfo);
        }
    }

    @Override
    public List<Order> getOrdersByUserId(int userId) {
        return orderDao.getOrdersByUserId(userId);
    }

    @Override
    public List<Orderinfo> getOrderInfosByOrderId(int orderId) {
        return orderDao.getOrderInfosByOrderId(orderId);
    }
    @Override
    public int delete(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("订单ID不能为空");
        }
        return orderDao.delete(id);
    }

    @Override
    public int addOrderAddress(OrderAddress orderAddress) {
        return orderDao.addOrderAddress(orderAddress);
    }

    @Override
    public String payment(Integer id) {
        Order order=orderDao.getOrderByID(id);
        if (order==null){
            throw new RuntimeException("订单不存在");
        }
       String status=order.getStatus();
        if ("待付款".equals(status)) {
            //准备支付--生成二维码
            String url=null;
            try {
               url= PaymentUtil.payment(order);
            }catch (Exception e){
                throw new RuntimeException("支付服务异常");
            }
            //生成二维码图片
            BufferedImage img=QrCodeUtil.generate(url, 300, 300);
            //将图片转换成Base64编码
            String qrcode=ImgUtil.toBase64(img,"png");
            System.out.println(qrcode);
            // 执行付款逻辑
            // 这里可以添加实际的付款处理代码，例如调用支付接口等
            // 假设付款成功后更新订单状态为已付款
            return qrcode;
        } else if ("已付款".equals(status)) {
            return "该订单已付款，无需重复支付";
        } else if ("商家已发货".equals(status)) {
            return "该订单已发货，无法进行付款操作";
        } else if ("已收货".equals(status)) {
            return "该订单已收货，无法进行付款操作";
        } else if ("已完成订单".equals(status)) {
            return "该订单已完成，无法进行付款操作";
        } else {
            return "未知订单状态，无法进行付款操作";
        }


    }

    @Override
    public int paymentSuccess(HashMap map) {
        //检查订单是否存在，是否是阿里后台的回调
        String code=(String)map.get("out_trade_no");
        System.out.println(code);
        return orderDao.paymentSuccess(code);
    }

    @Override
    public Order getOrderByID(Integer id) {
       return orderDao.getOrderByID(id);
    }
    @Override
    public List<Order> getOrders(Page page, String text){
        return orderDao.getOrders(page,text);
    }

    @Override
    public int getCount(String text) {
        return orderDao.getCount(text);
    }

    @Transactional
    @Override
    public void updateOrder(OrderUpdateDTO orderUpdateDTO) {
        orderDao.updateOrder(orderUpdateDTO);
        orderDao.updateOrderAddress(orderUpdateDTO);
    }

    @Override
    public boolean updateOrderStatus(OrderUpdateStatusDTO dto) {
        int rows = orderDao.updateOrderStatus(dto);
        return rows > 0;
    }

}